import { select } from 'd3-selection'
import mitter from '@/mitt'

export function graphNodeLinks (nodeContainer) {
  nodeContainer
    .selectAll('.x-mind-nodetheme')
    .selectAll('.xmind-node-link, .xmind-node-topiclink')
    .remove()

  const linkNodes = nodeContainer
    .selectAll('.x-mind-nodetheme')
    .filter(n => n.data.link)

  linkNodes
    .append('g')
    .attr('class', 'xmind-node-link')
    .attr('transform', d => {
      return `translate(0, ${-d.data.foreignObjectHeight / 2 + (d.style.linkSize + 2) / 2})`
    })
    .on('click', event => event.stopPropagation())
    .append('svg')
    .attr('x', d => d.x + d.width - d.style.margin._r - (d.style.linkSize) - (d.data.comment ? 8 + (d.style.linkSize) : 0))
    .attr('y', d => d.y + d.height - d.style.margin._t - (d.style.linkSize + 2) - d.tagLineHeight - 1)
    .append('a')
    .attr('target', '_blank')
    .attr('xlink:title', d => d.data.link)
    .attr('href', d => `${d.data.link}`)
    .append('svg')
    .attr('width', d => d.style.linkSize + 2)
    .attr('height', d => d.style.linkSize + 2)
    .attr('fill', d => d.style.textStyle.color)
    .attr('viewBox', '0 0 1024 1024')
    .html(select('#icon-link1').node().innerHTML)
    .append('rect')
    .attr('x', 0)
    .attr('y', 0)
    .attr('width', 1024)
    .attr('height', 1024)
    .attr('fill', 'transparent')

  const topiclinkNodes = nodeContainer
    .selectAll('.x-mind-nodetheme')
    .filter(n => n.data.topiclink)

  topiclinkNodes
    .append('g')
    .attr('class', 'xmind-node-topiclink')
    .attr('transform', d => {
      return `translate(0, ${-d.data.foreignObjectHeight / 2 + (d.style.linkSize + 2) / 2})`
    })
    .on('click', function (event) {
      event.stopPropagation()
      const topiclink = select(this).datum().data.topiclink
      mitter.emit('topiclink-handler-click', topiclink)
    })
    .append('svg')
    .attr('x', d => {
      const offsetX = [d.data.comment, d.data.link].filter(Boolean).reduce((prev) => {
        prev += (d.style.linkSize + 8)
        return prev
      }, 0)
      return d.x + d.width - d.style.margin._r - d.style.linkSize - offsetX
    })
    .attr('y', d => d.y + d.height - d.style.margin._t - d.style.linkSize - d.tagLineHeight - 1)
    .append('svg')
    .attr('width', d => d.style.linkSize)
    .attr('height', d => d.style.linkSize)
    .attr('fill', d => d.style.textStyle.color)
    .attr('viewBox', '0 0 1024 1024')
    .html(select('#icon-zhifeiji_line').node().innerHTML)
    .append('rect')
    .attr('x', 0)
    .attr('y', 0)
    .attr('width', 1024)
    .attr('height', 1024)
    .attr('fill', 'transparent')
}
